package cn.cl.controller;

import cn.cl.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 标题：
 * 作者：何处是归程
 * 时间：2020/3/29 - 13:18
 */
@ControllerAdvice
public class MyExceptionHandler {
//	@ExceptionHandler(UserNotExistException.class)
//	@ResponseBody
//	public Map<String, Object> handleException(Exception e) {
//		Map<String, Object> map = new HashMap<>();
//		map.put("code", "user.no");
//		map.put("message", e.getMessage());
//		return map;
//	}

	@ExceptionHandler(UserNotExistException.class)
	public String handleException(Exception e, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		// 传入我们自己的错误状态码 4xx 5xx 否则就不会进入错误页面
		/**
		 * Integer statusCode = (Integer) request
		 .getAttribute("javax.servlet.error.status_code");
		 */
		request.setAttribute("javax.servlet.error.status_code", 404);
		map.put("code", "user.no");
		map.put("message", e.getMessage());
		request.setAttribute("ext", map);
		return "forward:/error";
	}
}
